<template>
  <div class="novel-reader">
    <div class="chapter-sidebar">
      <div class="sidebar-header">
        <h2>{{ novelTitle }}</h2>
        <div class="chapter-filter">
          <input v-model="searchChapter" placeholder="搜索章节..." />
        </div>
      </div>
      <div class="chapter-list">
        <div v-for="chapter in filteredChapters" :key="chapter.id"
          :class="['chapter-item', { 'active': currentChapterId === String(chapter.id) }]"
          @click="loadChapter(String(chapter.id))">
          <span class="chapter-number">{{ chapter.sort }}.</span>
          <span class="chapter-title">{{ chapter.title }}</span>
        </div>
      </div>
      <div class="chapter-pagination">
        <button @click="changeChapterPage(currentChapterPage - 1)" :disabled="currentChapterPage <= 1">上一页</button>
        <span>{{ currentChapterPage }} / {{ totalChapterPages }}</span>
        <button @click="changeChapterPage(currentChapterPage + 1)"
          :disabled="currentChapterPage >= totalChapterPages">下一页</button>
      </div>
    </div>
    <div class="chapter-content">
      <div class="content-header">
        <button @click="goBack" class="back-button">← 返回列表</button>
        <h3>{{ currentChapterTitle }}</h3>
      </div>
      <div class="content-body" v-if="currentChapterContent">
        <p v-for="(paragraph, index) in currentChapterContent.split('\n')" :key="index" class="content-paragraph">{{
          paragraph }}</p>
      </div>
      <div class="loading" v-else>加载中...</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { NovelChapter } from '@/dataType/novelType';
import type { PageResponse } from '@/dataType/pageType';
import { novelService } from '@/services/novelService';

const route = useRoute();
const router = useRouter();
const novelId = route.params.novelId as string;

// Novel and chapter state
const novelTitle = ref('');
const chapters = ref<PageResponse<NovelChapter>>({ records: [], total: 0, current: 1, size: 20 });
const currentChapterId = ref('');
const currentChapterTitle = ref('');
const currentChapterContent = ref('');
const searchChapter = ref('');

// Pagination state
const currentChapterPage = ref(1);
const chapterPageSize = ref(20);
const totalChapterPages = computed(() => Math.ceil(chapters.value.total / chapterPageSize.value));

// Filtered chapters based on search
const filteredChapters = computed(() => {
  if (!searchChapter.value) return chapters.value.records;
  return chapters.value.records.filter(chapter =>
    chapter.title.toLowerCase().includes(searchChapter.value.toLowerCase())
  );
});

// Fetch chapter list
const fetchChapters = async () => {
  chapters.value = await novelService.getNovelChapterList(
    currentChapterPage.value,
    chapterPageSize.value,
    novelId
  );
  // Set novel title from first chapter if available
  if (chapters.value.records.length > 0 && !novelTitle.value) {
    novelTitle.value = chapters.value.records[0].title || '未知小说';
  }
  // Load first chapter if none selected
  if (chapters.value.records.length > 0 && !currentChapterId.value) {
    loadChapter(String(chapters.value.records[0].id));
  }
};

// Load specific chapter content
const loadChapter = async (chapterId: string) => {
  currentChapterId.value = chapterId;
  const chapter = await novelService.getNovelChapterDetail(chapterId);
  if (chapter) {
    currentChapterTitle.value = chapter.title;
    currentChapterContent.value = chapter.content;
    // Scroll to top of content
    document.querySelector('.content-body')?.scrollTo(0, 0);
  }
};

// Change chapter page
const changeChapterPage = (page: number) => {
  if (page >= 1 && page <= totalChapterPages.value) {
    currentChapterPage.value = page;
    fetchChapters();
  }
};

// Go back to novel list
const goBack = () => {
  router.push('/novel');
};

// Initial load
onMounted(async () => {
  // 获取小说详情
  const novelDetail = await novelService.getNovelDetail(novelId);
  if (novelDetail) {
    novelTitle.value = novelDetail.title;
  } else {
    novelTitle.value = '未知小说';
  }
  // 获取章节列表
  fetchChapters();
});
</script>

<style scoped>
.novel-reader {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.chapter-sidebar {
  width: 300px;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f9fafb;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.sidebar-header h2 {
  margin: 0 0 12px 0;
  font-size: 1.2rem;
  color: #111827;
}

.chapter-filter input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.9rem;
}

.chapter-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.chapter-item {
  padding: 10px 12px;
  margin-bottom: 4px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
}

.chapter-item:hover {
  background-color: #f3f4f6;
}

.chapter-item.active {
  background-color: #e0f2fe;
  border-left: 3px solid #3b82f6;
}

.chapter-number {
  font-weight: bold;
  margin-right: 8px;
  color: #4b5563;
  min-width: 24px;
}

.chapter-title {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chapter-pagination {
  padding: 12px 16px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.chapter-pagination button {
  padding: 6px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
}

.chapter-pagination button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.chapter-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.content-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-button {
  padding: 6px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

.content-header h3 {
  margin: 0;
  font-size: 1.5rem;
  color: #111827;
}

.content-body {
  flex: 1;
  overflow-y: auto;
  padding: 24px 48px;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

.content-paragraph {
  margin: 0 0 1.5rem 0;
  line-height: 1.8;
  font-size: 1.1rem;
  color: #374151;
}

.loading {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #6b7280;
  font-size: 1.2rem;
}

@media (max-width: 768px) {
  .novel-reader {
    flex-direction: column;
  }

  .chapter-sidebar {
    width: 100%;
    height: 40%;
  }

  .content-body {
    padding: 16px;
  }
}
</style>